module.exports = function(req,res,next){
  function getRemoteIp(req) {
    try {
      let xForwardedFor = req.headers['x-forwarded-for']
      if (xForwardedFor) {
        let xForwardedForList = xForwardedFor.split(',')
        if (xForwardedForList && xForwardedForList.length) {
          return xForwardedForList[0]
        }
      } else {
        return req.headers['remote_addr'] || req.headers['remoteip']
      }
    } catch (error) {
      
    }
    return null
  }

  let userIp = getRemoteIp(req)
  let cookie = req.headers['cookie']
  if (!userIp) {
    next()
    return;
  }
  let userIpEx = userIp.replace(/\./g, "\\.")
  let ipReg = new RegExp(`user_address\=${userIpEx};?`)
  if (!cookie || !ipReg.test(cookie)) {
    res.cookie('user_address',userIp)
  }

  next()
}